package com.example.personalizededucationsystem.controller;

import com.example.personalizededucationsystem.dto.dto.ClassAnalyticsResponseDto;
import com.example.personalizededucationsystem.dto.dto.DynamicQuestionRequestDto;
import com.example.personalizededucationsystem.dto.dto.DynamicQuestionResponseDto;
import com.example.personalizededucationsystem.dto.request.QuestionRequest;
import com.example.personalizededucationsystem.dto.response.QuestionResponse;
import com.example.personalizededucationsystem.model.KnowledgePoint;
import com.example.personalizededucationsystem.model.Question;
import com.example.personalizededucationsystem.model.User;
import com.example.personalizededucationsystem.service.AIAssistanceService;
import com.example.personalizededucationsystem.service.AnalysisService;
import com.example.personalizededucationsystem.service.KnowledgeService;
import com.example.personalizededucationsystem.service.QuestionBankService;
import com.example.personalizededucationsystem.utils.ApprovalStatus;
import com.example.personalizededucationsystem.utils.IP_VALUE;
import com.example.personalizededucationsystem.utils.PagedResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@CrossOrigin(origins = IP_VALUE.IP)
@RestController
@RequestMapping("/api/teacher")
@PreAuthorize("hasRole('TEACHER')")
public class TeacherController {

    private final AnalysisService analysisService;
    private final QuestionBankService questionBankService;
    private final KnowledgeService knowledgeService;
    private final AIAssistanceService aiAssistanceService;

    @Autowired
    public TeacherController(AnalysisService analysisService, QuestionBankService questionBankService, KnowledgeService knowledgeService, AIAssistanceService aiAssistanceService) {
        this.analysisService = analysisService;
        this.questionBankService = questionBankService;
        this.knowledgeService = knowledgeService;
        this.aiAssistanceService = aiAssistanceService;
    }

    @GetMapping("/classes/{classId}/analytics")
    public ResponseEntity<ClassAnalyticsResponseDto> getClassAnalytics(@PathVariable Long classId, @AuthenticationPrincipal User currentUser) {
        ClassAnalyticsResponseDto analytics = analysisService.getAnalyticsForClass(classId, currentUser);
        return ResponseEntity.ok(analytics);
    }

    @GetMapping("questions/{page}")
    public ResponseEntity<PagedResult<QuestionResponse>> getApprovedQuestions(@PathVariable int page, @RequestParam(required = false) String keyword, @RequestParam(required = false) String subject) {
        return ResponseEntity.ok(new PagedResult<>(questionBankService.getApprovedQuestions(page, keyword, subject).getData().stream().map(QuestionResponse::fromEntity).collect(Collectors.toList()), questionBankService.getApprovedQuestions(page, keyword, subject).getTotal()));
    }

    @PostMapping("/questions/create")
    public ResponseEntity<Question> createQuestion(@RequestBody QuestionRequest request, @AuthenticationPrincipal User currentUser) {
        Question createdQuestion = questionBankService.createQuestion(request, currentUser);
        return new ResponseEntity<>(createdQuestion, HttpStatus.CREATED);
    }

    @PostMapping("/questions/generate")
    public ResponseEntity<DynamicQuestionResponseDto> generateQuestion(@RequestBody DynamicQuestionRequestDto request) {
        DynamicQuestionResponseDto response = aiAssistanceService.generateQuestionFromAI(request.knowledge_point_name(), request.subject(), request.question_type(), request.difficulty());
        if (response == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return ResponseEntity.ok(response);
    }

    @GetMapping("/knowledge-points/APPROVED/{page}")
    public ResponseEntity<PagedResult<KnowledgePoint>> getKnowledgePoints(@PathVariable int page, @RequestParam(required = false) String keyword, @RequestParam String subject) {
        return ResponseEntity.ok(knowledgeService.getKnowledgePointsByStatusAndSubjects(ApprovalStatus.APPROVED, page, keyword, subject));
    }
}
